package com.baozhun.mall.common.util

import com.baozhun.mall.common.network.mCommonApiService
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.ext.request
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File

/**
 * @Title：上传图片工具类
 * @Description：
 * @Author：xuefeng.zhu
 * @Since：2023/2/12
 * @Version：1.0.0
 */
class UploadFileHelper {
    var mFileUrl = arrayListOf<String>()

    companion object {
        fun getInstance() = InstanceHelper.sSingle
    }

    object InstanceHelper {
        val sSingle = UploadFileHelper()
    }

    /**
     * 创建bodyPart
     */
    private fun createBodyPart(file: File): List<MultipartBody.Part> {
        var builder = MultipartBody.Builder().setType(MultipartBody.FORM) //表单类型
        var body = RequestBody.create(MediaType.parse("multipart/form-data"), file)
        builder.addFormDataPart("file", file.name, body) //添加图片数据
        return builder.build().parts()
    }

    /**
     * 上传单个文件
     */
    fun uploadSingleFile(viewModel: BaseViewModel, file: File, successCallback: (picUrl: String) -> Unit) {
        viewModel.request({ mCommonApiService.uploadPic(createBodyPart(file)) }, {
            successCallback.invoke(it.url)
        }, isShowDialog = true)
    }

    /**
     * 上传多个文件
     */
    fun uploadMultiFile(viewModel: BaseViewModel, files: MutableList<String>, uploadPosition: Int = 0, successCallback: ((urlList: List<String>) -> Unit)? = null) {
        if (files.isNullOrEmpty()) {
            successCallback?.invoke(arrayListOf())
            return
        }
        var uploadPositionTemp = uploadPosition
        uploadSingleFile(viewModel, File(files[uploadPositionTemp])) {
            uploadPositionTemp++
            mFileUrl.add(it)
            if (uploadPositionTemp < files.size) {
                uploadMultiFile(viewModel, files, uploadPositionTemp, successCallback)
            } else {
                successCallback?.invoke(mFileUrl.clone() as List<String>)
                mFileUrl.clear()
            }
        }
    }
}